package edu.mju.eduuser.controller;


import edu.mju.commonutils.JwtUtils;
import edu.mju.commonutils.ReturnCode;
import edu.mju.commonutils.orderVo.UserMemberOrder;
import edu.mju.eduuser.entity.StudyMember;
import edu.mju.eduuser.entity.vo.UserRegisterVo;
import edu.mju.eduuser.service.StudyMemberService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xiaoxin
 * @since 2020-09-27
 *
 */

@RestController
@RequestMapping("/eduUser/study-member")
//@CrossOrigin
public class StudyMemberController {

    @Autowired
    private StudyMemberService studyMemberService;

    /**
     * 实现登录
     * @param studyMember 登录的消息
     * @return json
     */
    @PostMapping("/login")
    public ReturnCode loginUser(@RequestBody StudyMember studyMember){
        //登录成功返回token
        String token = studyMemberService.login(studyMember);
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return ReturnCode.success().data(map);
    }


    /**
     * 用户注册
     * @param userRegisterVo 用户数据信息封装在UserRegisterVo种
     * @return json
     */
    @PostMapping("/register")
    public ReturnCode register(@RequestBody UserRegisterVo userRegisterVo){
        studyMemberService.register(userRegisterVo);
        return ReturnCode.success();
    }


    /**
     *  根据token获取用户信息
     * @param request HttpServletRequest
     * @return json
     */
    @GetMapping("/getUserInfo")
    public ReturnCode getUserInfo(HttpServletRequest request){
        //调用jwt工具类
        String userId = JwtUtils.getUserIdByJwtToken(request);

        //根据用户Id查询数据库
        StudyMember getUser = studyMemberService.getById(userId);

        //获取的用户信息放入map
        Map<String,Object> map = new HashMap<>();
        map.put("userInfo",getUser);

        return ReturnCode.success().data(map);
    }

    /**
     * 用户订单
     * 根据用户id获取用户信息
     *
     */
    @PostMapping("/getUserInfoOrder/{id}")
    public UserMemberOrder getUserInfoOrder(@PathVariable String id){
        StudyMember studyMember = studyMemberService.getById(id);
        UserMemberOrder userMemberOrder = new UserMemberOrder();
        BeanUtils.copyProperties(studyMember,userMemberOrder);
        return userMemberOrder;
    }

    /**
     * 查询某一天注册人数
     * @param day 某一天
     * @return json格式
     */
    @GetMapping("/countRegister/{day}")
    public ReturnCode countRegister(@PathVariable String day){

        Integer count = studyMemberService.countRegister(day);

        Map<String,Object> map = new HashMap<>();
        map.put("countRegister",count);

        return ReturnCode.success().data(map);
    }



}

